package com.ruoyi.quartz.task;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.monitortask.domain.MonitorTaskRecord;
import com.ruoyi.system.monitortask.domain.MonitoringErr;
import com.ruoyi.system.monitortask.mapper.MonitorTaskGoodsMapper;
import com.ruoyi.system.monitortask.mapper.MonitorTaskMapper;
import com.ruoyi.system.monitortask.mapper.MonitoringErrMapper;
import com.ruoyi.system.monitortask.service.IMonitorTaskRecordService;
import com.ruoyi.system.monitortask.vo.MonitorTaskGoodsVo;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.lang.reflect.Array;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
@Slf4j
public class GoodsMonitorTask {

    @Autowired
    private MonitorTaskMapper monitorTaskMapper;
    @Autowired
    private MonitorTaskGoodsMapper monitorTaskGoodsMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private IMonitorTaskRecordService monitorTaskRecordService;
    @Autowired
    private MonitoringErrMapper monitoringErrMapper;


    @Autowired
    private GoodsInfoMapper goodsInfoMapper;
    @Scheduled(cron = "0 0 3 1/3 * ?")
    public void executeTX() {
        List<Long> ids = new ArrayList<>();
        ids.add(2L);
        ids.add(3L);
        ids.add(5L);
        ids.add(6L);
        ids.add(8L);
        ids.add(10L);
        ids.add(25L);
        ids.add(26L);
        List<Map<String, Object>> goodsInfos = goodsInfoMapper.selectGoodsAccountAndType(ids);
        MonitorTaskRecord monitorTaskRecord = null;
        int count = 0;
        int countcount = 0;
        for (Map<String, Object> monitorTaskGoodsVo : goodsInfos) {
            //调用破晓的找回监控
            String accountNumber = MapUtils.getString(monitorTaskGoodsVo,"accountNumber");
            String securityPhone = MapUtils.getString(monitorTaskGoodsVo,"securityPhone");
            //监控记录开始赋值
            monitorTaskRecord = new MonitorTaskRecord();
            monitorTaskRecord.setCreateId(1L);
            monitorTaskRecord.setMonitorTaskId(0L);
            //类型1掉绑监控 2转手监控
            monitorTaskRecord.setMonitorTaskType(1);
            monitorTaskRecord.setGoodsId(MapUtils.getLong(monitorTaskGoodsVo,"id"));
            monitorTaskRecord.setGameId(MapUtils.getLong(monitorTaskGoodsVo,"gameId"));
            monitorTaskRecord.setGameName(MapUtils.getString(monitorTaskGoodsVo,"gameName"));

            monitorTaskRecord.setRemark("账号和密保手机不能为空");
            int res = 1;
            if (StringUtils.isNotEmpty(accountNumber) && StringUtils.isNotEmpty(securityPhone)) {
                if (isQQNumberValid(accountNumber)) {
                    JSONObject jsonObject = checkGamePX(accountNumber, securityPhone);
                    res = handleRes(jsonObject, 1L, monitorTaskRecord);
                } else {
                    monitorTaskRecord.setRemark("账号不是有效的qq号");
                }
            }
            monitorTaskRecordService.save(monitorTaskRecord);
            if (res == 1) {
                //正常进行
            } else if (res == 2) {
                //租游乐直接查询
            } else if (res == 3) {
                count++;
                if (count >= 30) {
                    MonitoringErr monitoringErr = new MonitoringErr();
                    monitoringErr.setErrText("添加监控任务异常已超过30次，今天任务都不执行了，需技术处理");
                    monitoringErrMapper.insert(monitoringErr);
                    break;
                }
            }
        }
    }


    //每3天 03:00:00 执行
//    @Scheduled(cron = "0 0 3 3 * ?")
    public void execute() {

        List<Map<String, Object>> tenantGoodsMonitorTask = monitorTaskMapper.getTenantGoodsMonitorTask();
        MonitorTaskRecord monitorTaskRecord = null;
        int count = 0;
        boolean isRun = true;
        for (Map<String, Object> map : tenantGoodsMonitorTask) {
            Long createId = MapUtils.getLong(map, "createId");
            if (!isRun) {
                break;
            }
            String taskIds = MapUtils.getString(map, "taskIds");
            if (StringUtils.isEmpty(taskIds)) {
                continue;
            }
            String[] taskIdArr = taskIds.split(",");
            for (String s : taskIdArr) {
                if (!isRun) {
                    break;
                }
                String[] split = s.split("=");
                if (Objects.isNull(split)) {
                    continue;
                }
                Long taskId = Long.valueOf(split[0]);
                Integer type = null;
                if (split.length > 1) {
                    type = Integer.valueOf(split[1]);
                }
                List<MonitorTaskGoodsVo> monitorTaskGoodsVos = null;
                if (type.intValue() == 1) {
                    monitorTaskGoodsVos = monitorTaskGoodsMapper.getMonitorTaskGoodsListDB2(taskId);
                } else if (type.intValue() == 2) {
                    monitorTaskGoodsVos = monitorTaskGoodsMapper.getMonitorTaskGoodsListZS2(taskId);
                }
                //更新last_date
                monitorTaskMapper.updateMonitorTask(taskId);
                if (CollectionUtils.isNotEmpty((monitorTaskGoodsVos))) {
                    for (MonitorTaskGoodsVo monitorTaskGoodsVo : monitorTaskGoodsVos) {
                        //调用破晓的找回监控
                        String accountNumber = monitorTaskGoodsVo.getAccountNumber();
                        String securityPhone = monitorTaskGoodsVo.getSecurityPhone();
                        //监控记录开始赋值
                        monitorTaskRecord = new MonitorTaskRecord();
                        monitorTaskRecord.setCreateId(createId);

                        monitorTaskRecord.setMonitorTaskId(taskId);
                        monitorTaskRecord.setMonitorTaskType(type);

                        monitorTaskRecord.setGoodsId(monitorTaskGoodsVo.getGoodsId());
                        monitorTaskRecord.setGameId(monitorTaskGoodsVo.getGameId());
                        monitorTaskRecord.setGameName(monitorTaskGoodsVo.getGameName());

                        monitorTaskRecord.setRemark("账号和密保手机不能为空");
                        int res = 1;
                        if (StringUtils.isNotEmpty(accountNumber) && StringUtils.isNotEmpty(securityPhone)) {
                            if (isQQNumberValid(accountNumber)) {
                                JSONObject jsonObject = checkGamePX(accountNumber, securityPhone);
                                res = handleRes(jsonObject, createId, monitorTaskRecord);
                            } else {
                                monitorTaskRecord.setRemark("账号不是有效的qq号");
                            }
                        }
                        monitorTaskRecordService.save(monitorTaskRecord);
                        if (res == 1) {
                            //正常进行
                        } else if (res == 2) {
                            //租游乐直接查询
                        } else if (res == 3) {
                            count++;
                            if (count >= 30) {
                                MonitoringErr monitoringErr = new MonitoringErr();
                                monitoringErr.setErrText("添加监控任务异常已超过30次，今天任务都不执行了，需技术处理");
                                monitoringErrMapper.insert(monitoringErr);
                                isRun = false;
                                break;
                            }
                        }

                    }
                }
            }
        }
    }


    public JSONObject checkGamePX(String accountNumber, String securityPhone) {
        String Key = "";
        String Secret = "";

        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("px_monitor_config");
        if (CollectionUtils.isNotEmpty(sysDictDataList)) {
            for (SysDictData dictData : sysDictDataList) {
                if ("Key".equals(dictData.getDictLabel())) {
                    Key = dictData.getDictValue();
                }
                if ("Secret".equals(dictData.getDictLabel())) {
                    Secret = dictData.getDictValue();
                }
            }
        }
        String body = HttpRequest.post("http://c.p74.cn/api/account/add")
                .form("account_number", accountNumber)
                .form("account_phone", securityPhone)
                .form("check_interval", "1")
                .form("interval_type", "0")
                .form("task_type", "3")
                .form("auto_switch_type", "0")
                .form("remark", "0")
                .form("apiKey", Key)
                .form("apiSecret", Secret).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(body);
        return jsonObject;
    }

    int handleRes(JSONObject jsonObject, Long createId,
                  MonitorTaskRecord monitorTaskRecord) {
        int flag = 1;
        String msg = jsonObject.getString("msg");
        String code = jsonObject.getString("code");
        String time = jsonObject.getString("time");

        if ("1".equals(code) && StringUtils.equals(msg, "ok")) {
            JSONObject data = jsonObject.getJSONObject("data");
            String checkId = data.getString("checkId");
            //继续给监控记录赋值
            monitorTaskRecord.setCheckId(checkId);
            monitorTaskRecord.setEnabled("1");
            monitorTaskRecord.setTaskStatus("0");
            monitorTaskRecord.setRemark(" ");
        } else {
            monitorTaskRecord.setRemark("添加失败,请联系管理员");
            flag = 3;
        }
        monitorTaskRecord.setMsg(msg);
        monitorTaskRecord.setCode(code);
        monitorTaskRecord.setTime(time);

        return flag;
    }

    /**
     * 判断是不是正确的QQ号
     *
     * @param qqNumber
     * @return
     */
    public boolean isQQNumberValid(String qqNumber) {
        // 判断QQ号码长度是否合法
        int length = qqNumber.length();
        if (length < 5 || length > 12) {
            return false;
        }

        // 判断QQ号码是否只包含数字
        for (int i = 0; i < length; i++) {
            if (!Character.isDigit(qqNumber.charAt(i))) {
                return false;
            }
        }

        // 判断QQ号码不能以0开头
        if (qqNumber.charAt(0) == '0') {
            return false;
        }

        return true;
    }

    public static void main(String[] args) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        System.out.println("当前日期：" + currentDate);

        Integer num = null;
        int numm = num;
        System.out.println(numm);

    }
}
